<template>
  <view class="container" :style="appThemeStyle">
    <u-tabs
      bg-color="transparent"
      :list="tabs"
      :is-scroll="false"
      :current="tabIndex"
      @change="changeTab"
    ></u-tabs>
    <!--渠道  -->
    <view class="channel-wrap" v-if="isChannel">
      <view class="channel-list">
        <view class="dis-flex flex-box">
          <view
            :class="['channel-item nowrap', { active: !channelId }]"
            @click="handleChannel('')"
          >
            全部
          </view>
          <view
            v-for="(item,index) in channelNormal"
            :key="index"
            :class="['channel-item nowrap', { active: channelId === item.thirdChannelId }]"
            @click="handleChannel(item.thirdChannelId)"
          >
            {{item.channelName}}
          </view>
        </view>
        <text class="iconfont" @click="handleChannelMore"> {{ !channelMore ? '&#xe6ac;' : '&#xe6ab;' }}</text>
      </view>
      <view v-if="channelMore" class="channel-list">
        <view class="dis-flex flex-box">
          <view
            v-for="(item,index) in channelOther"
            :key="index"
            :class="['channel-item', { active: channelId === item.thirdChannelId }]"
            @click="handleChannel(item.thirdChannelId)"
          >
            {{item.channelName}}
          </view>
        </view>
      </view>
    </view>
    <!-- 营业数据分析 -->
    <view class="dashboard">
      <view class="title">营业数据分析</view>
      <view class="gmv-total">
        <view class="gmv-item">
          <view class="name">GMV <text class="iconfont circle" @click="handleTips(1)">&#xe6b1;</text></view>
          <view class="number price-icon"><text>{{ (gmv.goodsAmount || 0).toFixed(2) }}</text></view>
          <view class="desc">
            <text class="float">较上期</text>
            <text :class="['iconfont normal', { active: gmv.goodsAmountGrowthRatio > 0 }]">{{ gmv.goodsAmountGrowthRatio > 0 ? '&#xe69c;' : '&#xe69a;' }}</text>
            <text class="normal price-icon" :class="{ active: gmv.goodsAmountGrowthRatio > 0 }">{{ gmv.goodsAmountGrowthRatio }}%</text>
          </view>
        </view>
        <view class="gmv-item">
          <view class="name">有效订单数 <text class="iconfont circle" @click="handleTips(2)">&#xe6b1;</text></view>
          <view class="number price-icon"><text>{{ gmv.validOrderCount }}</text></view>
          <view class="desc">
            <text class="float">较上期</text>
            <text :class="['iconfont normal', { active: gmv.validOrderCountGrowthRatio > 0 }]">{{ gmv.validOrderCountGrowthRatio > 0 ? '&#xe69c;' : '&#xe69a;' }}</text>
            <text class="normal price-icon" :class="{ active: gmv.validOrderCountGrowthRatio > 0 }">{{ gmv.validOrderCountGrowthRatio }}%</text>
          </view>
        </view>
        <view class="gmv-item">
          <view class="name">总补贴 <text class="iconfont circle" @click="handleTips(3)">&#xe6b1;</text></view>
          <view class="number price-icon"><text>{{ (gmv.discountPrice || 0).toFixed(2) }}</text></view>
          <view class="desc">
            <text class="float">较上期</text>
            <text :class="['iconfont normal', { active: gmv.discountPriceGrowthRatio > 0 }]">{{ gmv.discountPriceGrowthRatio > 0 ? '&#xe69c;' : '&#xe69a;' }}</text>
            <text class="normal price-icon" :class="{ active: gmv.discountPriceGrowthRatio > 0 }">{{ gmv.discountPriceGrowthRatio }}%</text>
          </view>
        </view>
      </view>
      <view class="compare">
        <view class="compare-cell">
          <view class="compare-cell__ele">
            <view class="name">有效GMV <text class="iconfont circle" @click="handleTips(4)">&#xe6b1;</text></view>
            <view class="number price-icon">{{ gmv.validAmount }}</view>
          </view>
          <view class="compare-cell__ele">
            <view class="name">上期</view>
            <view class="number price-icon">{{ gmv.priorValidAmount}}</view>
          </view>
          <view class="compare-cell__ele">
            <view class="name">{{ gmv.validAmountGrowthRatio > 0 ? '增长' : '降低' }}</view>
            <view class="number">
              <text :class="['iconfont normal', { active: gmv.validAmountGrowthRatio > 0 }]">{{ gmv.validAmountGrowthRatio > 0 ? '&#xe69c;' : '&#xe69a;' }}</text>
              <text class="normal price-icon" :class="{ active: gmv.validAmountGrowthRatio > 0 }">{{ gmv.validAmountGrowthRatio }}%</text>
            </view>
          </view>
        </view>
        <view class="compare-cell">
          <view class="compare-cell__ele">
            <view class="name">单均价 <text class="iconfont circle" @click="handleTips(5)">&#xe6b1;</text></view>
            <view class="number price-icon">{{ gmv.avgPrice }}</view>
          </view>
          <view class="compare-cell__ele">
            <view class="name">上期</view>
            <view class="number price-icon">{{ gmv.priorAvgPrice }}</view>
          </view>
          <view class="compare-cell__ele">
            <view class="name">{{ gmv.avgPriceGrowthRatio > 0 ? '增长' : '降低' }}</view>
            <view class="number">
              <text :class="['iconfont normal', { active: gmv.avgPriceGrowthRatio > 0 }]">{{ gmv.avgPriceGrowthRatio > 0 ? '&#xe69c;' : '&#xe69a;' }}</text>
              <text class="normal price-icon" :class="{ active: gmv.avgPriceGrowthRatio > 0 }">{{ gmv.avgPriceGrowthRatio }}%</text>
            </view>
          </view>
        </view>
        <view class="compare-cell" v-if="businessType === 0">
          <view class="compare-cell__ele">
            <view class="name">会员总数</view>
            <view class="number price-icon">{{ gmv.memberCount }}</view>
          </view>
          <view class="compare-cell__ele">
            <view class="name">上期</view>
            <view class="number price-icon">{{ gmv.priorMemberCount }}</view>
          </view>
          <view class="compare-cell__ele">
            <view class="name">{{ gmv.memberCountGrowthRatio > 0 ? '增长' : '降低' }}</view>
            <view class="number">
              <text :class="['iconfont normal', { active: gmv.memberCountGrowthRatio > 0 }]">{{ gmv.memberCountGrowthRatio > 0 ? '&#xe69c;' : '&#xe69a;' }}</text>
              <text class="normal price-icon" :class="{ active: gmv.memberCountGrowthRatio > 0 }">{{ gmv.memberCountGrowthRatio }}%</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- 趋势对比分析 -->
    <view class="sales-compare">
      <view class="title">趋势对比分析</view>
      <view class="select-list">
        <view
          :class="['select-item', { active: index === trendIndex }]"
          v-for="(item, index) in trendList"
          :key="index"
          @click="trendItem(index)"
        >
          {{ item.title }}
        </view>
      </view>
      <view class="charts">
        <qiun-data-charts
          :canvas2d="true"
          canvasId="chartsTrend"
          type="line"
          :localdata="trendData"
          background="none"
        />
      </view>
    </view>
    <!-- 销售渠道占比 -->
    <view class="sales-compare">
      <view class="title">销售渠道占比</view>
      <view class="select-list">
        <view
          :class="['select-item', { active: index === currentIndex }]"
          v-for="(item, index) in selectList"
          :key="index"
          @click="selectItem(index)"
        >
          {{ item.title }}
        </view>
      </view>
      <view class="charts">
        <qiun-data-charts
          :opts="opts"
          type="pie"
          :localdata="localData"
        />
      </view>
    </view>
    <!-- 商品销售排行 -->
    <view class="sales-compare">
      <view class="title">商品销售排行</view>
      <view class="sales-rank" v-if="salesRank.length">
        <view class="sales-item" v-for="(item, index) in salesRank" :key="index">
          <view class="goods-name">
            <image :src="$image('/storeminiapp/icon_app_new.png')"/>
            <view class="name">{{ item.goodsName }}</view>
          </view>
          <view class="between padding">
            <text class="label">GMV</text>
            <text class="value">{{ item.gmv }}</text>
          </view>
          <view class="between">
            <text class="label">订单数</text>
            <text class="value">{{ item.orderNum }}单</text>
          </view>
        </view>
      </view>
      <Empty tips="这里空空如也～" v-else />
    </view>

    <!-- 日历组件 -->
    <u-calendar class="calendar" max-date="2050-01-01" v-model="visible" mode="range" @change="changeDate"></u-calendar>
  </view>
</template>

<script>

import store from '@/store'
import Empty from '@/components/empty'
import * as DashboardApi from '@/api/dashboard'

export default {
  name: "index",
  components: {
    Empty
  },
  data() {
    return {
      opts: {
        extra: {
          pie: {
            activeOpacity: 0.5,
            activeRadius: 10,
            offsetAngle: 0,
            labelWidth: 15,
            border: true,
            borderWidth: 1,
            borderColor: "#FFFFFF"
          }
        },
        legend: {
          lineHeight: 24
        }
      },
      tabIndex: 0,
      tabs: [
        { name: '今日' },
        { name: '昨日' },
        { name: '近3日' },
        { name: '近7日' },
        { name: '自定义' }
      ],
      visible: false,
      trendList: [
        { title: 'GMV' },
        { title: '有效订单数' },
        { title: '总补贴' },
        { title: '净GMV' },
        { title: '单均价' },
        { title: '会员总数' }
      ],
      trendIndex: 0,
      selectList: [
        { title: '营业额' },
        { title: '有效订单数' }
      ],
      currentIndex: 0,
      queryParams: {
        start: this.$moment().format("YYYY-MM-DD 00:00:00"),
        end: this.$moment().format("YYYY-MM-DD 23:59:59"),
        timeType: 1,
        thirdChannelId: '',
        deliveryType: ''
      },
      trendData: [],
      localData: [],
      salesRank: [],
      gmv: {},
      channelId: '',
      isChannel: false,
      channelMore: false
    }
  },
  computed: {
    store() {
      return store.getters.store
    },
    shopId() {
      return this.store.id
    },
    channels() {
      return store.getters.channels
    },
    channelNormal() {
      return this.channels.slice(0, 3)
    },
    channelOther() {
      return this.channels.slice(3)
    },
    businessType() {
      return store.getters.businessType
    }
  },
  onLoad() {
    if (this.businessType !== 0) this.trendList.pop()
    this.onRefreshPage()
  },
  methods: {
    handleChannel(id) {
      this.channelId = id
      this.queryParams = {
        ...this.queryParams,
        thirdChannelId: id
      }
      this.onRefreshPage()
    },
    handleChannelMore() {
      this.channelMore = !this.channelMore
    },
    trendItem(index) {
      this.trendIndex = index
      this.getOrderTrendData()
    },
    selectItem(index) {
      this.currentIndex = index
      this.getShopChannelData()
    },
    changeTab(index) {
      this.tabIndex = index
      this.isChannel = false
      switch (index) {
        case 0:
          this.queryParams = {
            ...this.queryParams,
            start: this.$moment().format("YYYY-MM-DD 00:00:00"),
            end: this.$moment().format("YYYY-MM-DD 23:59:59")
          }
          break;
        case 1:
          this.queryParams = {
            ...this.queryParams,
            start: this.$moment().add(-1, 'days').format("YYYY-MM-DD 00:00:00"),
            end: this.$moment().add(-1, 'days').format("YYYY-MM-DD 23:59:59")
          }
          break;
        case 2:
          this.queryParams = {
            ...this.queryParams,
            start: this.$moment().add(-2, 'days').format("YYYY-MM-DD 00:00:00"),
            end: this.$moment().format("YYYY-MM-DD 23:59:59")
          }
          break;
        case 3:
          this.queryParams = {
            ...this.queryParams,
            start: this.$moment().add(-6, 'days').format("YYYY-MM-DD 00:00:00"),
            end: this.$moment().format("YYYY-MM-DD 23:59:59")
          }
          break;
        case 4:
          this.visible = true
          return;
        default:
          break;
      }
      this.currentIndex = 0
      this.onRefreshPage()
    },
    changeDate(e) {
      this.isChannel = true
      this.queryParams = {
        ...this.queryParams,
        start: this.$moment(e.startDate).format("YYYY-MM-DD 00:00:00"),
        end: this.$moment(e.endDate).format("YYYY-MM-DD 23:59:59")
      }
      this.currentIndex = 0
      this.onRefreshPage()
    },
    onRefreshPage() {
      if (this.businessType !== 0) {
        this.queryParams.organizationIds = this.shopId
      } else {
        delete this.queryParams.organizationIds
      }
      this.getDashboard()
      this.getOrderTrendData()
      this.getShopChannelData()
      this.getTopData()
    },
    getDashboard() {
      DashboardApi.dashboard(this.queryParams).then(res => {
        this.gmv = res.data
      })
    },
    getOrderTrendData() {
      DashboardApi.getOrderTrendData(this.queryParams).then(res => {
        const { data } = res
        let localData = []
        for (let i = 0; i < data.length; i++) {
          const item = data[i]
          const text = ((item.time).replace(/月/, ".")).replace(/日/, "") || ""
          switch (this.trendIndex) {
            case 0:
              localData.push({
                value: item.goodsAmount || "",
                text,
                group: 'GMV'
              })
              break;
            case 1:
              localData.push({
                value: item.orderCount || "",
                text,
                group: '有效订单数'
              })
              break;
            case 2:
              localData.push({
                value: item.discountPrice || "",
                text,
                group: '总补贴'
              })
              break;
            case 3:
              localData.push({
                value: item.validAmount || "",
                text,
                group: '有效GMV'
              })
              break;
            case 4:
              localData.push({
                value: item.avgPrice || "",
                text,
                group: '单均价'
              })
              break;
            case 5:
              localData.push({
                value: item.memberCount || "",
                text,
                group: '会员总数'
              })
              break;
          }
        }
        if (localData.length > 24) {
          localData = [...localData.slice(0, 3), ...localData.slice(-13)]
        }
        this.trendData = localData.length > 7 ? localData.filter((_, index) => index % 2 === 0) : localData
      })
    },
    getShopChannelData() {
      DashboardApi.getShopChannelData(this.queryParams).then(res => {
        const { data } = res
        this.localData = data.map(item => {
          return {
            value: this.currentIndex === 0 ? item.gmv : item.y,
            text: item.channelName,
          }
        })
      })
    },
    getTopData() {
      DashboardApi.getTopData(this.queryParams).then(res => {
        this.salesRank = res.data
      })
    },
    handleTips(value) {
      switch (value) {
        case 1:
          this.$toast('商品原价流水总额', 3000)
          break;
        case 2:
          this.$toast('已接单且未整单取消的订单数量', 3000)
          break;
        case 3:
          this.$toast('商家承担补贴+渠道承担补贴+品牌承担补贴', 3000)
          break;
        case 4:
          this.$toast('商品原价-商品单品补贴-商家整单补贴-商家运费补贴', 3000)
          break;
        case 5:
          this.$toast('商品原价-商品单品补贴-商家整单补贴-商家支付补贴', 3000)
          break;
        default:
          break;
      }
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  padding: 24rpx;

  .channel-wrap {
    width: 100%;
    background: #FFFFFF;
    padding: 20rpx;
    margin-top: 10px;
    box-sizing: border-box;
    border-radius: 16rpx;

    .channel-list {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .channel-item {
        width: 68px;
        margin: 10rpx 13rpx;
        height: 26px;
        background: #FFFFFF;
        border-radius: 2px;
        border: 1px solid #EEEEEE;
        display: flex;
        justify-content: center;
        align-items: center;

        &.active {
          background: #2D71FD;
          color: #FFFFFF;
        }
      }

      .nowrap {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .iconfont {
        font-size: 40rpx;
      }
    }
  }

  .dashboard {
    background: #fff;
    padding: 24rpx;
    margin-top: 16rpx;
    border-radius: 16rpx;

    .title {
      font-size: 32rpx;
      font-weight: bold;
    }

    .more {
      font-size: 26rpx;
      color: #999999;
    }

    .gmv-total {
      display: flex;
      margin-top: 32rpx;

      .gmv-item {
        flex: 1;
        text-align: left;

        .name {
          font-size: 26rpx;
        }

        .number {
          font-weight: bold;
          margin: 12rpx 0;

          text {
            font-size: 38rpx;
          }
        }

        .desc {
          font-size: 24rpx;
          color: #999999;

          .float {
            margin-right: 8rpx;
          }

          .normal {
            color: #47D034;

            &.active {
              color: red;
            }
          }
        }
      }
    }

    .compare {
      margin-top: 32rpx;

      .compare-cell {
        background: #F5F6F9;
        border-radius: 16rpx;
        padding: 20rpx;
        margin-bottom: 16rpx;
        display: flex;

        &__ele {
          flex: 1;
          text-align: center;

          .name {
            font-size: 26rpx;
            color: #66696E;
          }

          .number {
            font-size: 30rpx;
            font-weight: bold;
            margin-top: 12rpx;
            display: flex;
            justify-content: center;
            align-items: center;

            .normal {
              color: #47D034;

              &.active {
                color: red;
              }
            }

            .iconfont {
              font-weight: normal;
            }
          }
        }
      }
    }
  }

  .sales-compare {
    background: #fff;
    padding: 24rpx;
    margin-top: 16rpx;
    border-radius: 16rpx;

    .title {
      font-size: 32rpx;
      font-weight: bold;
    }

    .select-list {
      margin-top: 32rpx;
      display: flex;
      flex-wrap: wrap;

      .select-item {
        margin-right: 16rpx;
        border-radius: 8rpx;
        border: 1rpx solid var(--eeeeee, #EEE);
        background: #FFF;
        font-size: 24rpx;
        color: #666666;
        padding: 10rpx 24rpx;
        margin-bottom: 16rpx;

        &.active {
          background: #f8f8f8;
          color: #333333;
          font-weight: bold;
        }
      }
    }

    .charts {
      background: #ffffff;
      width: 100%;
      height: 500rpx;
    }

    .sales-rank {

      .sales-item {
        padding: 30rpx 0;
        border-bottom: 1rpx dashed #999;

        .goods-name {
          display: flex;
          align-items: center;

          image {
            width: 40rpx;
            height: 40rpx;
            margin-right: 16rpx;
          }

          .name {
            font-weight: bold;
            font-size: 26rpx;
          }
        }

        .between {
          display: flex;
          align-items: center;
          justify-content: space-between;

          .label {
            font-size: 26rpx;
            color: #666666;
          }

          .value {
            font-size: 28rpx;
            color: #333333;
          }
        }

        .padding {
          padding: 30rpx 0;
        }
      }
    }
  }
}
</style>
